<?php

namespace app\model;

use think\helper\Str;
use think\Model;

class ProductCode extends Model
{
    public function autoCoupon(): array
    {
        $param = request()->post();
        $codeType = $pwdType = 1;
        if ($param['codeType'] == 'char') {
            $codeType = 0;
        }

        if ($param['codeType'] == "string") {
            $codeType = null;
        }
        if ($param['pwdType'] == 'char') {
            $pwdType = 0;
        }

        if ($param['pwdType'] == "string") {
            $pwdType = null;
        }
        $data = [];
        for ($i = 0; $i < $param['number']; $i++) {
            $data[] = [
                'code' => Str::random($param['codeLength'], $codeType),
                'pwd' => $param['checkPwd'] ? Str::random($param['pwdLength'], $pwdType) : null,
                'pid' => $param['pid'],
                'aid' => $param['aid']
            ];
        }
        $this->saveAll($data);
        return $data;
    }

    public function importCoupon(): array
    {
        $param = request()->post();
        $data = array_map(function ($v) use ($param) {
            $v['aid'] = $param['aid'];
            $v['pid'] = $param['pid'];
            return $v;
        }, $param['data']);
        $this->startTrans();
        $this->saveAll($data);
        // 更新库存
        app(ProductAttr::class)->where(['id' => $param['aid']])->inc('stock', count($data))->save();
        $this->commit();
        return $data;
    }
}
